package top.kaoshanji.ch12;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.ch12.threads.Bank;

/**
 * 代码清单 ch12-01：线程简单示例(12.1节、转账)
 * @see top.kaoshanji.ch12.threads.Bank
 * author kaoshanji
 * ^_^
 * create time 2024/11/29 10:28
 */
public class ThreadTest {

    private static final Logger logger = LogManager.getLogger(ThreadTest.class);

    public static final int DELAY = 10;
    public static final int STEPS = 100;
    public static final double MAX_AMOUNT = 1000;

    public static void main(String[] args) {
        logger.info("...代码清单 ch12-01：线程简单示例(12.1节、转账)...");

        // 4个账户，每个账户 100000
        var bank = new Bank(4, 100000);

        // 练习一下 lambda 表达式
        Runnable task1 = () -> {
            try {
                for (int i = 0; i < STEPS; i++) {
                    double amount = MAX_AMOUNT * Math.random();
                    // 账号0 向 账户1 转账
                    bank.transfer(0, 1, amount);
                    Thread.sleep((int)(DELAY * Math.random()));
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        };


        Runnable task2 = () -> {
            try {
                for (int i = 0; i < STEPS; i++) {
                    double amount = MAX_AMOUNT * Math.random();
                    bank.transfer(2, 3, amount);
                    Thread.sleep((int)(DELAY * Math.random()));
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        };


        new Thread(task1).start();
        new Thread(task2).start();

    }
}
